import { defineStore } from 'pinia'
import { setToken, getToken, removeToken } from '@/utils/auth'
import fetchApi from '@/api/login'
// import { useRequest } from 'vue-request'
import { useRouter } from 'vue-router'
import usePermissionStore from '../permission'

export  const useUserStore = defineStore(
  'app-user',
  {
    state: () => {
        return {
          userName: '',
          nickName: '',
          account: '',
          auths: [],
          modules: [],
          role: -1,
          token: getToken(),
          avatar: '',
        }
    },
    actions: {
      setAuth(auths) {
        this.auths = auths
      },
      setToken(info) {
        this.token = info ?? '';
        setToken(info)
      },
      resetState() {
        this.userName = '';
        this.nickName = '';
        this.account = '';
        this.role = -1;
        this.avatar = '';
        this.token = '';
        this.auths = [];
        this.modules = [];
      },
      async Login(params) {
          const router = useRouter()
          const data = await fetchApi.login(params)
          
          if (data) {
            const { token, userName, userId, avatar, auths, role, modules  } = data
            this.setToken(token)
            this.$patch({
              userName, userId, avatar, auths, role, modules
            })
          }
          return data
          
          // login(data).then(res => {
          //   if (res.code === 200) {
          //     const { token, userName, userId, avatar, auths, role } = res.result
          //     console.log(res.result)
              
          //     setToken(token)
          //     commit('SET_TOKEN', token)
          //     commit('SET_USERNAME', userName)
          //     commit('SET_USERID', userId)
          //     commit('SET_AVATAR', avatar)
          //     commit('SET_AUTHS', auths)
          //     commit('SET_ROLE', role)
          //     resolve()
          //   }
          // }).catch(error => {
          //   reject(error)
          // })
      },
      Logout() {
        this.resetState()
        usePermissionStore().resetState()
        removeToken()
        // 路由表重置
        location.reload();
      }
    },
    persist: {
      enabled: true,
      strategies: [
        {storage: sessionStorage, paths: ['token', 'userName', 'nickName', 'auths']}
      ]
    }
  }
)